package com.itboye.hutouben.activity.driverrepair;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.itboye.hutouben.R;
import com.itboye.hutouben.base.BaseActivity;
import com.itboye.hutouben.util.MyTask;

import java.io.File;

public class MapActivity extends BaseActivity {
    private LocationClient locationClient;//定位客户�?
    private MyLocationListener locationListener = new MyLocationListener();
    private MapView mvMap;//百度地图控件
    private BaiduMap baiduMap;
    //    private ZoomControlsView zcvZomm;//缩放控件
    private static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    String mobile, addres;
    String lat;
    String lng;
    private final int BAIDU_READ_PHONE_STATE = 127;
    EditText ed_getAddress;
    ImageView img_center;
    ImageView close_icon;
    TextView add_shap_title_tv;
    TextView map_ok;

   LatLng zb;
    private LatLng ll;

    double latt;
    double lngg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //必须在setContentView�?
        setContentView(R.layout.map_activity);
        add_shap_title_tv.setText("选择位置");
        //创建定位客户�?
        locationClient = new LocationClient(getApplicationContext());
        //注册监听�?
        locationClient.registerLocationListener(locationListener);
        initMap();

        getPersimmions();
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    /*
     *判断当前是否是6.0版本
     */
    private void getPersimmions() {
        // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            isCameraPermission(this, 1);
            //     requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE + "", Manifest.permission.ACCESS_COARSE_LOCATION + "", Manifest.permission.ACCESS_FINE_LOCATION + "", Manifest.permission.READ_EXTERNAL_STORAGE + "", Manifest.permission.WRITE_EXTERNAL_STORAGE + ""}, BAIDU_READ_PHONE_STATE);
        } else {
            initMap();
        }
    }

    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public static boolean isCameraPermission(Activity context, int requestCode) {
        if (Build.VERSION.SDK_INT >= 23) {
            int aPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE);
            int bPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION);
            int cPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
            int dPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
            int ePermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
            if (aPermission != PackageManager.PERMISSION_GRANTED || bPermission != PackageManager.PERMISSION_GRANTED || cPermission != PackageManager.PERMISSION_GRANTED || dPermission != PackageManager.PERMISSION_GRANTED || ePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(context, PERMISSIONS, requestCode);
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            // requestCode即所声明的权限获取码，在checkSelfPermission时传入
            case BAIDU_READ_PHONE_STATE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获取到权限，作相应处理（调用定位SDK应当确保相关权限均被授权，否则可能引起定位失败）
                    initMap();
                } else {
                    // 没有获取到权限，做特殊处理
                }
                break;
            default:
                break;
        }
    }

    /**
     * 初始化地�?
     */
    private void initMap() {
        //获取地图控件
        mvMap = (MapView) findViewById(R.id.mv_map);
        mvMap.showZoomControls(false);//隐藏缩放控件
        //获取地图对象控制�?
        baiduMap = mvMap.getMap();
        baiduMap.setBuildingsEnabled(true);//设置显示楼体
        baiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(19f));//设置地图状�??
//        baiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
//            @Override
//            public void onMapClick(LatLng latLng) {
////                Intent intent=new Intent();
////                intent.putExtra("lng",latLng.longitude);
////                intent.putExtra("lat",latLng.latitude);
////                intent.putExtra("address",latLng.describeContents());
////                setResult(102,intent);
////                finish();
//                //实例化一个地理编码查询对象
//                GeoCoder geoCoder = GeoCoder.newInstance();
//                //设置反地理编码位置坐标
//                ReverseGeoCodeOption op = new ReverseGeoCodeOption();
//                op.location(latLng);
//                //发起反地理编码请求(经纬度->地址信息)
//                geoCoder.reverseGeoCode(op);
//                geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
//
//                    @Override
//                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
//                        //获取点击的坐标地址
//                        String address = arg0.getAddress();
//                        Intent intent = new Intent();
//                        intent.putExtra("address", address);
//                        setResult(102, intent);
//                        finish();
//                        System.out.println("address=" + address);
//                    }
//
//                    @Override
//                    public void onGetGeoCodeResult(GeoCodeResult arg0) {
//                    }
//                });
//            }
//
//            @Override
//            public boolean onMapPoiClick(MapPoi mapPoi) {
//                return false;
//            }
//
//
//        });
        //获取缩放控件
//        zcvZomm = (ZoomControlsView) findViewById(R.id.zcv_zoom);
//        zcvZomm.setMapView(mvMap);//设置百度地图控件
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy
        );//可选，默认高精度，设置定位模式，高精度，低功耗，仅设备
        option.setCoorType("bd09ll");//可选，默认gcj02，设置返回的定位结果坐标系

        int span = 0;
        option.setScanSpan(span);//可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的
//        option.setIsNeedAddress(true);//可选，设置是否需要地址信息，默认不需要
//        option.setOpenGps(true);//可选，默认false,设置是否使用gps
//        option.setLocationNotify(true);//可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果
//        option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
//        option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
//        option.setIgnoreKillProcess(false);//可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死
//        option.SetIgnoreCacheException(false);//可选，默认false，设置是否收集CRASH信息，默认收集
//        option.setEnableSimulateGps(false);//可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        locationClient.setLocOption(option);
        locationClient.start();

        addres = getIntent().getStringExtra("addres");
        mobile = getIntent().getStringExtra("mobile");
        lat = getIntent().getStringExtra("lat");
        lng = getIntent().getStringExtra("lng");
        baiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener);
    }

    BaiduMap.OnMapStatusChangeListener onMapStatusChangeListener = new BaiduMap.OnMapStatusChangeListener() {

        @Override
        public void onMapStatusChangeStart(MapStatus arg0) {

        }

        //状态结束
        @Override
        public void onMapStatusChangeFinish(MapStatus arg0) {

            //获取百度地图的中心点
            LatLng latLng = arg0.target;
            double longitude = latLng.longitude;//经度
            double latitude = latLng.latitude;//维度

            LatLng ptCenter = new LatLng(latitude, longitude);
            //实例化一个地理编码查询对象
            GeoCoder geoCoder = GeoCoder.newInstance();
            //设置反地理编码位置坐标
            ReverseGeoCodeOption op = new ReverseGeoCodeOption();
            op.location(ptCenter);
            //发起反地理编码请求(经纬度->地址信息)
            geoCoder.reverseGeoCode(op);
            geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                @Override
                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                    //获取点击的坐标地址
//                    String address = arg0.getAddress();
//                    Intent intent = new Intent();
//                    intent.putExtra("address", address);
//                    setResult(102, intent);
//                    finish();

                    latt=arg0.getLocation().latitude;
                    lngg=arg0.getLocation().longitude;
                    address = arg0.getAddress();
                    MyTask myTask = new MyTask();
                    myTask.setAddress(address);
                    myTask.setTextView(ed_getAddress);
                    myTask.execute();
                }

                @Override
                public void onGetGeoCodeResult(GeoCodeResult arg0) {
                }
            });
        }

        @Override
        public void onMapStatusChange(MapStatus arg0) {

        }
    };

    private View.OnClickListener onclicklister = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // TODO Auto-generated method stub
            switch (view.getId()) {
                case R.id.open_camera:
                    break;
                case R.id.pick_image:
                    break;
            }
        }
    };


    private boolean isInstallByread(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }

    String address = "";

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_center:

                break;
            case R.id.close_icon:
                finish();
                break;
            case R.id.map_ok:
                //获取点击的坐标地址
                Intent intent = new Intent();
                intent.putExtra("address", address);
                intent.putExtra("lngg", lngg+"");
                intent.putExtra("latt", latt+"");
                setResult(102, intent);
                finish();
                break;
        }
    }


    /**
     * 实现百度定位监听�?
     *
     * @author Arvin_Li
     */
    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null) return;
            //创建地理坐标点对�?
            LatLng point = new LatLng(location.getLatitude(), location.getLongitude());
//            //将国测局坐标转为百度坐标
//            point = gcjTobaidu(point);
            //�?启定位图�?

            baiduMap.setMyLocationConfigeration(null);
            baiduMap.setMyLocationEnabled(true);
            //构�?�定位数�?
//            MyLocationData locData = new MyLocationData.Builder()
//                    .accuracy(location.getRadius())//设置位置的精度信�?
//                    .direction(location.getDirection())//设置获取到的方向信息，顺时针0-360
//                    .latitude(point.latitude)//设置定位数据的纬�?
//                    .longitude(point.longitude)//设置定位数据的经�?
//                    .build();//构建生成定位数据对象
//            //设置定位数据
//            baiduMap.setMyLocationData(locData);

            //构建定位图标
//            constructionLocationIcon(point);
            ll = new LatLng(location.getLatitude(),
                    location.getLongitude());
            //实例化一个地理编码查询对象
            GeoCoder geoCoder = GeoCoder.newInstance();
            //设置反地理编码位置坐标
            ReverseGeoCodeOption op = new ReverseGeoCodeOption();
            op.location(ll);
            //发起反地理编码请求(经纬度->地址信息)
            geoCoder.reverseGeoCode(op);
            geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {

                @Override
                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult arg0) {
                    //获取点击的坐标地址
//                    String address = arg0.getAddress();
//                    Intent intent = new Intent();
//                    intent.putExtra("address", address);
//                    setResult(102, intent);
//                    finish();
                    zb = new LatLng(arg0.getLocation().latitude,
                            arg0.getLocation().longitude);

//                    latt=arg0.getLocation().latitude;
//                    lngg=arg0.getLocation().longitude;
//                    Log.d("OOOOO",latt+"====="+lngg+"");

                    address = arg0.getAddress();
                    MyTask myTask = new MyTask();
                    myTask.setAddress(address);
                    myTask.setTextView(ed_getAddress);
                    myTask.execute();
                    MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(zb);
                    baiduMap.setMapStatus(u);
                }

                @Override
                public void onGetGeoCodeResult(GeoCodeResult arg0) {
                }
            });
//            mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(ll));

            //新加
            //BitmapDescriptor bitmap = BitmapDescriptorFactory.fromResource(R.drawable.current_addres_point_icon);
            //准备 marker option 添加 marker 使用
            //MarkerOptions markerOptions = new MarkerOptions().icon(bitmap).position(ll);
            //获取添加的 marker ,可以触发点击事件获取位置
            //marker = (Marker) mBaiduMap.addOverlay(markerOptions);


//            MyTask myTask = new MyTask();
//            myTask.setAddress(location.getAddress().address);
//            myTask.setTextView(ed_getAddress);
//            myTask.execute();
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }


    }

    /**
     * 构建定位图标
     *
     * @param point 图标位置
     */
    private void constructionLocationIcon(LatLng point) {
        //创建Marker图标
        BitmapDescriptor descriptor = BitmapDescriptorFactory.fromResource(R.drawable.xk);
        //构建MarkerOption，用于在地图上添加Marker
        OverlayOptions options = new MarkerOptions()
                .icon(descriptor)//设置图标
                .position(point)//设置图标位置
                .draggable(true)//允许拖拽
                .zIndex(5);//设置图标层次
        //清空地图�?有的 Overlay 覆盖物以�? InfoWindow
        baiduMap.clear();
        //在地图上添加图标
        baiduMap.addOverlay(options);
        //设置定位图层配置信息，只有先允许定位图层后设置定位图层配置信息才会生�?
        baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(com.baidu.mapapi.map.MyLocationConfiguration.LocationMode.FOLLOWING, true, descriptor));
        //关闭定位图层
        baiduMap.setMyLocationEnabled(false);

//        MyTask myTask = new MyTask();
//        myTask.setAddress(address);
//        myTask.setTextView(ed_getAddress);
//        myTask.execute();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mvMap.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mvMap.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != locationClient && locationClient.isStarted()) {
            locationClient.stop();//停止定位
        }
        locationClient = null;
        try {
            mvMap.onDestroy();
        } catch (Exception e) {

        }
    }

    /**
     * 国测�?转换百度经纬�?
     *
     * @param point
     * @return
     */
    public static LatLng gcjTobaidu(LatLng point) {
        // double x = gg_lon, y = gg_lat;
        double x = point.longitude, y = point.latitude;
        double z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
        double theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
        double bd_lon = z * Math.cos(theta) + 0.0065;
        double bd_lat = z * Math.sin(theta) + 0.006;
        LatLng point1 = new LatLng(bd_lat, bd_lon);
        return point1;
    }


}
